##=============================================================================
## Appendix Figure 26
##=============================================================================

##-----------------
# clear environment
rm(list=ls())
options(stringsAsFactors = FALSE, scipen = 999)
# source("R/functions.R")

seed <- sample.int(.Machine$integer.max, 1)
set.seed(seed)

ipak <- function(pkg){new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if(length(new.pkg)) install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}

packages <- c("tidyverse")

ipak(packages)

##---------
# Load data
#setwd("/Users/austinknuppe/Library/CloudStorage/Dropbox/Ukraine2022WartimeSurvey/Paper_peace/final_version_oct_2024/replication-scripts")
load("~/Desktop/clean_ukraine_data.RData")

plot <- dat %>% 
  filter(home_lang == 2) %>%
  dplyr::select(id, wave, survival_mindset_z, compromise_idx_terr_z) %>% 
  mutate(survival_binary = ifelse(survival_mindset_z > 0.71, 1, 0)) %>% 
  mutate(wave = factor(wave, labels = c("July 2022", "February 2023"))) %>%
  mutate(survival_binary = factor(survival_binary, labels = c("Low", "High"))) %>%
  drop_na(survival_binary) %>% 
  group_by(wave, survival_binary) %>% 
  summarise(mean = mean(compromise_idx_terr_z, na.rm = TRUE), 
            sd = sd(compromise_idx_terr_z, na.rm = TRUE), 
            n = sum(!is.na(compromise_idx_terr_z))) %>% 
  mutate(se = sd / sqrt(n),
         lower = mean - qnorm(0.975) * se,
         upper  = mean + qnorm(0.975) * se) %>% 
  dplyr::select(wave, survival_binary, mean, lower, upper) 

ggplot(plot, aes(x = wave, y = mean, color = survival_binary,
                 group = survival_binary)) +
  geom_point(size = 5, position = position_jitterdodge(dodge.width = 0.1,
                                                       seed = 1234)) +
  geom_linerange(aes(x = factor(wave), ymin = lower, ymax = upper, 
                     color = factor(survival_binary)), lwd = 2,
                 position = position_jitterdodge(dodge.width = 0.1,
                                                 seed = 1234)) +
  scale_y_continuous(limits = c(-0.5, 1.5),
                     breaks = c(-1, -0.5, 0, 0.5, 1.0, 1.5)) +
  labs(title = "Difference in Compromise Between Waves Among Russian-Speaking Respondents",
       y = "Compromise (z-std)",
       x = "",
       color = "Survival Mindset") +
  geom_hline(yintercept = 0, colour = gray(1/2), size = 1, lty = 2) +
  scale_color_grey() +
  theme_bw(base_size = 20) +
  theme(legend.position = "bottom",
        legend.direction = "horizontal",
        panel.spacing = unit(0.1, "lines"),
        strip.text.x = element_text(size = 18)) +
  guides(color=guide_legend(override.aes=list(fill=NA)))

rm(list = ls())
##=============================================================================
## End of File
##=============================================================================